/***********************************/
/*    AJAX func to edit an Eval    */
/***********************************/

var criteria_id             = [];
var criteria_array          = [];
var new_criteria_array      = [];
var newCriteria             = 0;
var maxHeader               = 0;
var newLevel                = 0;
var delete_header           = [''];
var delete_criteria         = [''];
var check_all               = 0;

function cleanTable(){
    $(".headerTab").remove();
    $(".criteriaLine").remove();
    criteria_id         = [];
    criteria_array      = [];
    new_criteria_array  = [];
    check_all           = 0;
    maxHeader           = 0;

    for (var i = 0; i < newCriteria; i++) {
        $('#nw_criteria_line_'+ i).remove();
    };
}

function check(id)
{
    var j = 0;

    $('input:checkbox').each(function () {
        //console.log(maxHeader);
        if ((j % (maxHeader + 1)) == id)
        {
            $(this).prop('checked', true);       
        }
        j++;
    });
}

function uncheck(id)
{
    var j = 0;

    $('input:checkbox').each(function () {
        
        if ((j % (maxHeader + 1)) == id)
        {
            $(this).prop('checked', false);
        }
        j++;
    });
}


function createNewEvaluationForm(idEval)
{
    criteria                    = [];
    level_mark                  = [];
    setToZero                   = [''];


    //old criteria
    $('[id^="criteria"]').each(function(){

        criteria_description_mark   = [];

        id_criteria             = $(this).attr('id');
        id_criteria             = id_criteria.split('_');
        id_criteria             = id_criteria[1];

        name_criteria           = $('#criteria_' + id_criteria).val();
        description_criteria    = $('#description_' + id_criteria).val();
        coeff_criteria          = $('#coefficient_' + id_criteria).val();
        criteria_zero           = 0;

        pageName                = document.location.href.match(/[^\/]+$/)[0];

        //description level mark
        $('#'+ id_criteria).find('[id^="header_"]').each(function(){
            id = $(this).attr('id');
            id = id.split('_');
            id = id[1];

            if ($(this).next().is(':checked'))
            {
                checked = 'checked';
            }
            else
            {
                checked = 'unchecked';
            }
            criteria_description_mark.push([id , $(this).val(), checked]);
        });
        

        $('#' + id_criteria ).find('[class^=new_header]').find('input:text').each(function(){
            if ($(this).next().is(':checked'))
            {
                checked = 'checked';
            }
            else
            {
                checked = 'unchecked';
            }
            criteria_description_mark.push(['new' , $(this).val(), checked]);
        });
        
        if($('#setToZero_' + id_criteria + ':checked').val() == "on")
        {
            criteria_zero = 1;
        }

        criteria.push([id_criteria, name_criteria, description_criteria, coeff_criteria, 'old', criteria_description_mark, criteria_zero]);
    });

    //new criteria
    $('[id^="new_criteria_"]').each(function(){
        criteria_description_mark = [];

        id_criteria             = $(this).attr('id');
        id_criteria             = id_criteria.split('_');
        id_criteria             = id_criteria[2];
        
        name_criteria           = $('#new_criteria_' + id_criteria).val();
        description_criteria    = $('#new_description_' + id_criteria).val();
        coeff_criteria          = $('#new_coeff_' + id_criteria).val();
        
        checked                 = '';

        $('#nw_criteria_line_' + id_criteria ).find('[class*=newLevel]').each(function(){
            if ($(this).next().is(':checked'))
            {
                checked = 'checked';
            }
            else
            {
                checked = 'unchecked';
            }
            criteria_description_mark.push(['new' , $(this).val(), checked]);
        });

        criteria.push([id_criteria, name_criteria, description_criteria, coeff_criteria, 'new', criteria_description_mark]);
    });

    $('[id^="level_mark_"]').each(function(){
        id                      = $(this).attr('id').split('_');
        id                      = id[2];

        if (id != 'new')
        {
            name_mark               = $('#level_' + id).val();
            mark                    = $('#level_mark_' + id).val();
        }
        else
        {
            input                   = $(this).prev();
            name_mark               = $(input).val();
            mark                    = $(this).val();
        }
        

        level_mark.push([id, name_mark, mark]);
    });

    $('[id^="setToZero_"]:checked').each(function(){
        id                      = $(this).attr('id').split('_');
        id                      = id[1];

        setToZero.push(id);
    });

    console.log(criteria, level_mark, setToZero, idEval, delete_header, delete_criteria);
    
    request = $.ajax({
        url:    'edit_evaluation_form.php',
        type:   'POST',
        data:   {   type : 'up',
                    criteria        : criteria,
                    level_mark      : level_mark,
                    set_to_zero     : setToZero,
                    id_eval         : idEval,
                    del_header      : delete_header,
                    del_criteria    : delete_criteria
                }
    });

    request.done(function (result) {
        //console.log(result);
        $('#myModal').modal('show');
    });

    request.fail(function (jqXHR, textStatus){
        console.log("Request AJAX failed : " + textStatus);
    });
}

$('#new_eval_validate').click(function(){

    var title = $('#title_eval').val();
    if ( title != '')
    {
         request = $.ajax({
            url:    'edit_evaluation_form.php',
            type:   'POST',
            data:   {   
                        name_eval : title,
                        type : 'check'
                    }
        });

        request.done(function (result) {
            //console.log(result);
            if (result != 0)
            {
                //console.log('Already exist !');

                $('#title_eval').css('border', '3px solid red');
                $('<b id="error_name_eval">Name already taken !</b>').insertAfter('#title_eval');
            }
            else 
            {
                $('#error_name_eval').remove();
                $('#title_eval').css('border', '');
                $('#add_new_eval').modal('hide');
                createNewEvaluationForm(title);
            }
        });
    } 
    else
    {
        $('#title_eval').css('border', '3px solid red');
    }
});
// VERIFIER SI LE COEFF N EST PAS EGAL A ZERO !
$('#saveAs').click(function(){
    var coeff = 0;
    var error = false;

    $('.coeff').each(function(){
        if ($(this).val() != '')
        {
            coeff += parseFloat($(this).val());
            if ($(this).val() == 0)
            {
                error = true;
            }
        }
    });

    if (error == true)
    {
        alert('Attention : un des coefficient est égal à 0 !');
        $('.coeff').css('border', '3px solid red');
    }
    else
    {
        if (coeff.toFixed(5) != 1)
        {
            alert("Attention ! Coefficient : " + coeff.toFixed(5));
            $('.coeff').css('border', '3px solid red');
        }
        else
        {
            $('.coeff').css('border', '');
            $('#add_new_eval').modal('show');
        }
    }
    
});

$('#normal').click(function(){
    $('#normal_div').show();
    $('#unacceptable_div').hide();
});

$('#unacceptable').click(function(){
    $('#normal_div').hide();
    $('#unacceptable_div').show();
});

$('#add_level_mark_validate').click(function () {
    mark_name   = $('#new_mark_name').val();
    mark_value  = $('#new_mark').val();
    type        = $('.btn.btn-default.btn-sm.active').attr('id');
    error       = false;

    $('[id^="level_"]').each(function (){
        if ($(this).val() == mark_name)
        {
            error = true;
        }
    });        

    if (type == 'normal')
    {
        if (mark_value == '' || mark_name == '' || $.isNumeric(mark_value) == false || mark_value > 20 || error == true)
        {
            $('.new_mark_div').addClass('has-error');
        }
        else 
        {
            nameHeader = 'new_header_'+ newLevel;
            new_level   = $('<th width="20%" class="headerTab header_'+ newLevel +'">').html('<span onclick="delLevelMark(\''+ nameHeader +'\');" class="input-group-addon btn btn-danger"><b>X</b></span><input id="level_'+ newLevel +'" class="form-control" type="text" value="'+ mark_name +'"><input id="level_mark_new"  class="form-control" type="text" value="'+ mark_value +'"><div onclick="check('+ check_all +');" style="cursor:pointer;"> Tout cocher</div><div style="cursor:pointer;" onclick="uncheck('+ check_all +');" > Tout décocher</div>');
        
            $('.description_criteria').each(function () {
                $("<td class='new_header_"+ newLevel +"'><input type='text' class='form-control newLevel'><input type='checkbox'></td>").insertBefore(this);
            });
            
            $(new_level).insertBefore('#notApply');
            $('#add_level_mark').modal('hide');
            newLevel++;
            maxHeader++;
        }    
    }
    else
    {
        nameHeader = 'new_header_'+ newLevel;
        new_level   = $('<th width="20%" class="headerTab header_'+ newLevel +'">').html('<span onclick="delLevelMark(\'' + nameHeader + '\');" class="input-group-addon btn btn-danger"><b>X</b></span><input id="level_unacceptable" class="form-control" type="text" value="Situation inacceptable"><input id="level_mark_unacceptable" class="form-control" type="text" value="0"><div onclick="check('+ check_all +');" style="cursor:pointer;"> Tout cocher</div><div style="cursor:pointer;" onclick="uncheck('+ check_all +');" > Tout décocher</div>');
        
        $('.description_criteria').each(function () {
            $("<td class='new_header_"+ newLevel +"'><input type='text' class='form-control'><input type='checkbox'></td>").insertBefore(this);
        });
        
        $(new_level).insertBefore('#notApply');
        $('#add_level_mark').modal('hide');
        newLevel++;
        maxHeader++;
    }
    check_all++;
});

$('#addLevelRating').click(function() {
    $('#add_level_mark').modal('show');
});

$('#addCriteria').click(function(){
    tdHtml              = '';
    criteriaName        = $("<td>").html($("<div class='input-group form-group'><span onclick='delCriteria("+ newCriteria +");' class='btn btn-danger input-group-addon'><b>X</b></span><input class='form-control' type='text' id='new_criteria_" + newCriteria + "'></div>"));
    criteriaDescription = $("<td>").html($("<input class='form-control' type='text' id='new_description_" + newCriteria + "'>"));
    criteriaCoeff       = $("<td>").html($("<input class='form-control coeff' type='text' id='new_coeff_" + newCriteria + "'>"));

    nb_td               = $('#headerTab').children('th').length;
    //Sub the 3 first column
    nb_td               -= 3;

    for (var i = 0; i < nb_td; i++)
    {
        if ((nb_td - i) == 1)
        {
            tdHtml += "<td class='description_criteria'><input type='checkbox' id='setToZero_" + newCriteria + "'></td>";
        }
        else 
        {
            tdHtml += "<td><input type='text' class='form-control newLevel' id='newCriteria_" + i + "'><input type='checkbox' id='checkBox_" + i + "'></td>";
        }
    };
    
    newLine             = $('<tr class="criteria_'+ newCriteria +'" id="nw_criteria_line_'+ newCriteria +'">').html(criteriaName.add(criteriaDescription.add(criteriaCoeff.add(tdHtml))));
    $(newLine).insertBefore('#footerTab');
    newCriteria++;
});

$('#updateEvaluation').click(function(){
    var coeff = 0;

    $('.coeff').each(function(){
        if ($(this).val() != '')
        {
            coeff += parseFloat($(this).val());    
        }
    });
    
    if (coeff.toFixed(5) != 1)
    {
        $('.coeff').css('border', '3px solid red');
        alert(' Coeff : ' + coeff.toFixed(2));
    }
    else
    {
        createNewEvaluationForm($('#selectedEvaluation').val());
    }
});

function delLevelMark(id)
{
    name = $('th.' + id).find('input').first().val();
    delete_header.push(name);
    $('.' + id).remove();
    console.log('th.' + id);
}

function delCriteria(id)
{
    $('.criteria_' + id).remove();    
    delete_criteria.push(id);
}

$('#selectEval').click(function (){

    idEval = $('#selectedEvaluation').val();
    
    if(idEval)
    {
        cleanTable();
    
        request = $.ajax({
            url:    'edit_evaluation_form.php',
            type:   'POST',
            data:   {id_eval : idEval}
        });

        request.done(function (result) {
            var obj             = jQuery.parseJSON(result);
            var headerTab       = '';
            var criteriaHtml    = '';
            var tdHtml          = '';

            //Display the header's tab
            for (var idx in obj.header)
            {
                //console.log("IDX : " + idx);
                nameHeader = "header_"+ idx;
                headerTab += '<th width="20%" class="headerTab header_'+ idx +'"><span onclick="delLevelMark(\''+ nameHeader +'\');" class="input-group-addon btn btn-danger"><b>X</b></span><input id="level_'+ obj.header[idx]['id'] +'" class="form-control" type="text" value="'+ obj.header[idx]['name'] +'"><input id="level_mark_'+ obj.header[idx]['id'] +'" class="form-control" type="text" value="'+ obj.header[idx]['mark'] +'"><div onclick="check('+ check_all +');" style="cursor:pointer;"> Tout cocher</div><div style="cursor:pointer;" onclick="uncheck('+ check_all +');" > Tout décocher</div></th>'; 
                check_all++;
                maxHeader++;
            }

            $(headerTab).insertAfter($('#coeff'));

            //Display Criteria's data
            for (var idx in obj.criteria)
            {
                tdHtml              = '';
                criteriaName        = $("<td width='20%'>").html('<div class="input-group form-group"><span onclick="delCriteria(' + obj.criteria[idx]['id'] + ');" class="btn btn-danger input-group-addon"><b>X</b></span><input class="form-group form-control" type="text" id="criteria_' + obj.criteria[idx]['id'] + '" value="'+ obj.criteria[idx]['name'] +'"></div>');
                criteriaDescription = $("<td>").html($("<input class='form-control' type='text' id='description_" + obj.criteria[idx]['id'] + "'>").val(obj.criteria[idx]['description']));
                criteriaCoefficient = $("<td>").html($("<input class='form-control coeff' type='text' id='coefficient_" + obj.criteria[idx]['id'] + "'>").val(obj.criteria[idx]['coefficient']));
                
                criteria_id.push(obj.criteria[idx]['id']);
                //console.log(obj.descriptionCriteria);
                for (var i in obj.descriptionCriteria)
                {
                    for (var y in obj.descriptionCriteria[i])
                    {
                        if (obj.criteria[idx]['id'] == obj.descriptionCriteria[i][y]['id_criteria'])
                        {
                            tdHtml += '<td class="header_'+ y +'"><input id="header_'+ obj.descriptionCriteria[i][y]['id'] +'" type="text" class="form-control" value="'+ obj.descriptionCriteria[i][y]['description'] +'">';
                            if (obj.descriptionCriteria[i][y]['activate'] == 1)
                            {
                                tdHtml += '<input type="checkbox" checked>';
                            }
                            else
                            {
                                tdHtml += '<input type="checkbox">';
                            }
                            tdHtml += '</td>';
                            newCriteria = i;
                        }
                    }
                }
                
                if (obj.criteria[idx]['set_to_zero'] == 1)
                {
                    inputChecked = 'checked';
                }
                else
                {
                    inputChecked = '';
                }

                tdHtml += '<td class="description_criteria"><input ' + inputChecked + ' type="checkbox" id="setToZero_' + obj.criteria[idx]['id'] + '"></td>';
                criteriaHtml = $('<tr class="criteriaLine criteria_'+ obj.criteria[idx]['id'] +'" id="' + obj.criteria[idx]['id'] + '">').html(criteriaName.add(criteriaDescription.add(criteriaCoefficient.add(tdHtml))));
                $(criteriaHtml).insertBefore('#footerTab');
            }
        });

        request.fail(function (jqXHR, textStatus){
            console.log("Request AJAX failed : " + textStatus);
        });

        $('#table_evaluation').show();
    }
});